//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package roadmap_user_api_serv

import (
	"context"
	"math"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/roadmap_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/roadmap_user_api"
)

type RoadmapUserApiImpl struct {
	roadmap_user_api.UnimplementedRoadmapUserApiServer
}

func (apiImpl *RoadmapUserApiImpl) GetLearnState(ctx context.Context, req *roadmap_user_api.GetLearnStateRequest) (*roadmap_user_api.GetLearnStateResponse, error) {
	learnState := &roadmap_user_api.LearnState{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_user_api.GetLearnStateResponse{
			Code:       roadmap_user_api.GetLearnStateResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			LearnState: learnState,
		}, nil
	}
	accessItemList, err := roadmap_dao.AccessRecordDao.ListByUser(ctx, sessionItem.UserId, 0, math.MaxInt64)
	if err != nil {
		return nil, err
	}
	learnState.AccessRecordCount = uint32(len(accessItemList))
	for _, accaccessItem := range accessItemList {
		learnState.DoneTopicCount += accaccessItem.DoneTopicCount
		learnState.TotalTopicCount += accaccessItem.TotalTopicCount
		learnState.DoneSubTopicCount += accaccessItem.DoneSubTopicCount
		learnState.TotalSubTopicCount += accaccessItem.TotalSubTopicCount
	}

	return &roadmap_user_api.GetLearnStateResponse{
		Code:       roadmap_user_api.GetLearnStateResponse_CODE_OK,
		LearnState: learnState,
	}, nil
}
